import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {Validators} from '@angular/forms';
import {FormBuilder} from '@angular/forms';
import {FormGroup} from '@angular/forms';
import {Params} from '@angular/router';
import {Router} from '@angular/router';
import {ActivatedRoute} from '@angular/router';
import {ToolsService} from '@shared/service/tools/tools.service';
import {ValidationService} from '@shared/service/validator/validator.service';
import {SignUpService} from '@sign-up/sign-up.service';


@Component({
  selector: 'ticketer-form',
  templateUrl: './ticketer-form.component.html',
  styleUrls: ['./ticketer-form.component.scss'],
  encapsulation: ViewEncapsulation.None

})
export class TicketerFormComponent implements OnInit {
  public selectHasChange = false;
  public ticketsForm: FormGroup;
  public tickets: Array<string> = [];
  public dataStore = {
    orderNumber: '',
    orderPrice: null
  };
  public error = {   // 错误验证的状态
    name: false,
    phone: false,
    ID: false,
    address: false,
    obtainType: false
  };
  public goodsCode = {
    goodsCode: ''
  };

  constructor(public route: ActivatedRoute,
              public router: Router,
              private formBuilder: FormBuilder,
              private signUpService: SignUpService,
              private tool: ToolsService) {
    this.route.queryParams.subscribe((params: Params) => {
      this.dataStore.orderNumber = params['orderNumber'];
      this.goodsCode = params['goodsCode'];
      this.getObtainType(params['goodsCode']);
      this.getOrderInfo(params['orderNumber']);
    });
  }

   // 表单初始化
  formInit() {
    this.ticketsForm = this.formBuilder.group({
      'name': ['', [Validators.required, Validators.minLength(2), ValidationService.nickNameValidator]],
      'ID': ['', [Validators.required, ValidationService.IDnumValidator]],
      'phone': ['', [Validators.required, ValidationService.accountValidator]],
      'address': ['', [Validators.required]],
      'obtainType': ['', [Validators.required]]
    });

  }

   // 表单单项输入错误提示
  nameCheck() {
    if (!this.ticketsForm.controls['name'].valid) {
      this.error.name = true;
    } else {
      this.error.name = false;
    }
  }

  IDCheck() {
    if (!this.ticketsForm.controls['ID'].valid && this.ticketsForm.controls['ID'].dirty) {
      this.error.ID = true;
    } else {
      this.error.ID = false;
    }
  }

   // 手机号错误提示
  phoneCheck() {
    if (!this.ticketsForm.controls['phone'].valid && this.ticketsForm.controls['phone'].dirty) {
      this.error.phone = true;
    } else {
      this.error.phone = false;
    }
  }

   // 地址错误提示
  addressCheck() {
    if (!this.ticketsForm.controls['address'].valid && this.ticketsForm.controls['address'].dirty) {
      this.error.address = true;
    } else {
      this.error.address = false;
    }
  }

 // 取票方式提示
  ticketChange() {
    this.selectHasChange = true;
    if (!this.ticketsForm.controls['obtainType'].valid && this.ticketsForm.controls['obtainType'].dirty) {
      this.error.obtainType = true;
    } else {
      this.error.obtainType = false;
    }
  }

  /**
   * @description 获取订单信息
   * @author ouyqx-691
   * @param orderNumber 订单编号
   */
  getOrderInfo(orderNumber) {
    this.tool.showLoading();
    this.signUpService.getOrderInfo(orderNumber).subscribe(res => {
      this.tool.hideLoading();
      if (res.result === '0' && res.data) {
        const orderInfo = res.data;
        const ticketsForm = this.ticketsForm.controls;
        ticketsForm['name'].setValue(orderInfo.receiptUserName);
        ticketsForm['phone'].setValue(orderInfo.phone);
        ticketsForm['address'].setValue(orderInfo.address);
        this.dataStore.orderPrice = orderInfo.total;
        this.nameCheck();
      }
    });
  }

  /**
   * @description 清楚文本框
   * @author ouyqx-691
   * @param name 文本框值
   */
  clearValue(name: string) {
    this.ticketsForm.controls[name].setValue('');
  }

  /**
   * @description 票务列表
   * @author zhoukf-691
   * @param Array
   */
  getObtainType(goodsCode) {
    this.tool.showLoading();
    this.signUpService.getObtainType(goodsCode).subscribe(res => {
      this.tool.hideLoading();
      if (res.result === '0') {
        this.tickets = res.data.valueTexts;
      }
    });
  }

  /**
   * @description 完善票务人信息
   * @author ouyqx-691
   * @date 2017-09-18
   */
  submitForm() {
    const formData = this.ticketsForm.controls;
    const orderNumber: string = this.dataStore.orderNumber;
    const data = {
      name: formData['name'].value, // 收货人
      mobile: formData['phone'].value, // 收货人手机号
      idNo: formData['ID'].value,
      address: formData['address'].value, // 详细地址
      orderNumber: orderNumber,
      obtainType: formData['obtainType'].value,
    };

    this.signUpService.insertTicketerInfo(data).subscribe(res => {
      if (res.result === '0') {
        // const orderPrice = this.dataStore.orderPrice;
        // if (orderPrice > 0) {
        //   this.router.navigate(['/payment'], {queryParams: {orderNumber: orderNumber}});
        // } else {
        //   this.router.navigate(['/payment/result'], {queryParams: {mchOrderNumber: orderNumber}});
        // }
        this.signUpService.goToPayOrResult(res.data, orderNumber);
      } else if (res.result === '13004') {
        this.tool.showToast('订单号不存在', 800);
      }
    });
  }

  ngOnInit() {
    this.formInit();
  }

}
